package com.mvvm.lib.base

import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.ToastUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.lxj.xpopup.impl.LoadingPopupView
import com.mvvm.lib.R
import java.lang.reflect.ParameterizedType


abstract class BaseVMActivity<VM : BaseViewModel, VB : ViewBinding> : BaseActivity<VB>() {

    protected lateinit var viewModel: VM


    //  private var dialog: MaterialDialog? = null

    protected open  var loadingPop: LoadingPopupView? = null

    protected open val userDialog = false

    override fun onCreate(savedInstanceState: Bundle?) {
        createViewModel()
        if (userDialog) {
            createLoadView()
        }
        lifecycle.addObserver(viewModel)
        //注册 UI事件
        registerDefUIChange()
        super.onCreate(savedInstanceState)
    }

    //创建加载框
    open fun createLoadView(maxWidth: Int = 240) {
        loadingPop=  XPopup.Builder(this)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .isViewMode(true)
            .hasShadowBg(false)
           // .maxWidth(maxWidth)
         //   .maxHeight(maxWidth)
           // .popupWidth(SizeUtils.dp2px(maxWidth))
           // .popupHeight(SizeUtils.dp2px(maxWidth)-30)
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .isLightNavigationBar(true)
            .asLoading("请求中...", R.layout.loading_view,LoadingPopupView.Style.Spinner)

    }

    /**
     * 注册 UI 事件
     */
    private fun registerDefUIChange() {
        viewModel.defUI.showDialog.observe(this) {
            showLoading(it)
        }
        viewModel.defUI.dismissDialog.observe(this) {
            dismissLoading()
        }
        viewModel.defUI.toastEvent.observe(this) {
            ToastUtils.showShort(it)
        }
        viewModel.defUI.msgEvent.observe(this) {
            handleEvent(it)
        }
    }

    override fun showLoading(info: String?) {
        if (userDialog) {
            loadingPop?.let {
                it.setTitle(info)
                if (!it.isShow) {
                    it.show()
                }
            }
        } else {
            super.showLoading(info)
        }

    }



    /**
     * 关闭等待框
     */
    override fun dismissLoading() {
        super.dismissLoading()
        loadingPop?.dismiss()
    }

    /**
     * 创建 ViewModel
     */
    @Suppress("UNCHECKED_CAST")
    private fun createViewModel() {
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val cls = type.actualTypeArguments[0] as Class<VM>
            viewModel = ViewModelProvider(viewModelStore, defaultViewModelProviderFactory)[cls]
        }
    }


}